package net.maku.api.module.storage;

import net.maku.api.module.storage.util.HttpUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 存储服务
 *
 * @author 阿沐 babamu@126.com
 */
public interface StorageService {
    /**
     * 文件路径
     * @param prefix 前缀
     * @param suffix 后缀
     * @return 返回上传路径
     */
    default String getPath(String prefix, String suffix) {
        //生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件路径
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String path = df.format(new Date()) + "/" + uuid;

        if(StringUtils.hasText(prefix)){
            path = prefix + "/" + path;
        }

        return path + "." + suffix;
    }

    /**
     * 文件上传
     * @param data    文件字节数组
     * @param path    文件路径，包含文件名
     * @return        返回http地址
     */
    String upload(byte[] data, String path);

    /**
     * 文件上传
     * @param data     文件字节数组
     * @param suffix   后缀
     * @return         返回http地址
     */
    String uploadSuffix(byte[] data, String suffix);

    /**
     * 文件上传
     * @param inputStream   字节流
     * @param path          文件路径，包含文件名
     * @return              返回http地址
     */
    String upload(InputStream inputStream, String path);

    /**
     * 文件上传
     * @param inputStream  字节流
     * @param suffix       后缀
     * @return             返回http地址
     */
    String uploadSuffix(InputStream inputStream, String suffix);

     /*
     获取上传文件路径，不包括文件名称
     */
     String getUploadPath();

    /*
    获取上传文件的URL，不包括文件名称
    */
    String getUploadUrl();

    default Boolean download(HttpServletResponse response, String url) throws IOException {

        InputStream object = HttpUtil.urlToInputStream(url);

        byte[] buf = new byte[1024];
        int length;
        response.reset();
        String name = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
        String fileName = URLDecoder.decode(name, "UTF-8") + url.substring(url.lastIndexOf("."));
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        OutputStream outputStream = response.getOutputStream();
        if (object != null){

            while ((length = object.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            outputStream.flush();
        }

        if (object != null){
            object.close();
        }
        outputStream.close();
        return true;
    }


}
